<template>
  <Modal
    v-model="form.visible"
    :width="1000"
    :mask-closable="false"
    :loading="loading"
    :title="form.data.pkInitial ? '修改活动信息' : '新增活动信息'"
    ok-text="提交"
    @on-ok="ok">

    <Row class="mt30 step-1" v-show="currentStep === 1">
      <Col span="18" offset="3">
        <RadioGroup v-model="form.data.act_type" type="button" size="large" style="display: block; width: 300px; margin: 0 auto;">
          <Radio
            v-for="(item, index) in actTypeCodeList"
            :label="item.code"
            :key="index"
            :disabled="item.code === 3 && matchStatus !== '2' ? 'disabled' : false">
            {{item.name}}
          </Radio>
        </RadioGroup>
        <div v-if="form.data.act_type === 1" class="step-1-con">俱乐部文案在此</div>
        <div v-if="form.data.act_type === 2" class="step-1-con">商业活动文案在此</div>
        <div v-if="form.data.act_type === 3" class="step-1-con">赛事文案在此(待处理)</div>
      </Col>
    </Row>

    <Row class="mt30 step-2" v-show="currentStep === 2">
      <Col span="16" offset="4">
        <Form ref="form" :model="form.data" :rules="ruleValidate" :label-width="120">
          <FormItem prop="act_name" label="活动名称">
            <Input v-model="form.data.act_name" placeholder="请输入活动名称"></Input>
          </FormItem>
          <FormItem label="活动地区" required>
            <Row>
              <Col span="8">
                <FormItem prop="province">
                  <Select v-model="form.data.province" placeholder="请选择省份">
                    <Option v-for="item in areaCodeList" :value="item.code" :key="item.code">{{item.name}}</Option>
                  </Select>
                </FormItem>
              </Col>
              <Col span="7" offset="1">
                <FormItem prop="city">
                  <Select v-model="form.data.city" placeholder="请选择城市">
                    <Option v-for="item in cityList" :value="'' + item.code" :key="item.code">{{item.name}}</Option>
                  </Select>
                </FormItem>
              </Col>
              <Col span="7" offset="1">
                <FormItem prop="county">
                  <Select v-model="form.data.county" placeholder="请选择区县">
                    <Option v-for="item in countyList" :value="'' + item.code" :key="item.code">{{item.name}}</Option>
                  </Select>
                </FormItem>
              </Col>
            </Row>
          </FormItem>
          <FormItem prop="act_year" label="年度">
            <Select v-model="form.data.act_year" placeholder="请选择年度">
              <Option v-for="item in actYearCodeList" :value="'' + item.code" :key="item.code">{{item.name}}</Option>
            </Select>
          </FormItem>
          <FormItem prop="pk_activity_year_plan" label="年度计划">
            <Select
              v-model="form.data.pk_activity_year_plan"
              filterable
              v-if="!yearplanLoading">
              <Option v-for="option in yearplanList" :value="option.pk_act_year_plan" :key="option.pk_act_year_plan">{{option.act_name}}</Option>
            </Select>
          </FormItem>
          <FormItem prop="act_sponsor" label="主办方">
            <Input type="text" v-model="form.data.act_sponsor" placeholder="请输入主办方" />
          </FormItem>
          <FormItem prop="act_organizer" label="协办方">
            <Input type="text" v-model="form.data.act_organizer" placeholder="请输入协办方" />
          </FormItem>
          <FormItem prop="act_bg" label="活动介绍">
            <Input type="textarea" v-model="form.data.act_bg" placeholder="请输入活动介绍" :rows="8" />
          </FormItem>
          <FormItem label="报名时间" required>
            <Row>
              <Col span="24">
                <Row>
                  <Col span="11">
                    <FormItem prop="signup_start_time">
                      <DatePicker type="datetime" :options="this.options.signup_start_time" style="width:100%" placeholder="选择时间" v-model="form.data.signup_start_time"></DatePicker>
                    </FormItem>
                  </Col>
                  <Col span="2" class="tc">-</Col>
                  <Col span="11">
                    <FormItem prop="signup_end_time">
                      <DatePicker type="datetime" :options="this.options.signup_end_time" style="width:100%" placeholder="选择时间" v-model="form.data.signup_end_time"></DatePicker>
                    </FormItem>
                  </Col>
                </Row>
              </Col>
            </Row>
          </FormItem>
          <FormItem label="活动时间" required>
            <Row>
              <Col span="24">
                <Row>
                  <Col span="11">
                    <FormItem prop="act_start_time">
                      <DatePicker type="datetime" :options="this.options.act_start_time" style="width:100%" placeholder="选择时间" v-model="form.data.act_start_time"></DatePicker>
                    </FormItem>
                  </Col>
                  <Col span="2" class="tc">-</Col>
                  <Col span="11">
                    <FormItem prop="act_end_time">
                      <DatePicker type="datetime" :options="this.options.act_end_time" style="width:100%" placeholder="选择时间" v-model="form.data.act_end_time"></DatePicker>
                    </FormItem>
                  </Col>
                </Row>
              </Col>
            </Row>
          </FormItem>
          <FormItem label="集合时间" required>
            <Row>
              <Col span="24">
                <Row>
                  <Col span="11">
                    <FormItem prop="conv_date">
                      <DatePicker type="datetime" style="width:100%" placeholder="选择时间" v-model="form.data.conv_date"></DatePicker>
                    </FormItem>
                  </Col>
                </Row>
              </Col>
              <Col span="12"></Col>
            </Row>
          </FormItem>
          <FormItem prop="conv_address" label="集合地点">
            <Input type="text" v-model="form.data.conv_address" placeholder="请输入集合地点"></Input>
          </FormItem>
          <FormItem prop="sign_up_total" label="拟报名人数">
            <InputNumber :max="99999" :min="1" v-model.number="form.data.sign_up_total" placeholder="请输入拟报名人数"></InputNumber>
          </FormItem>
          <FormItem prop="explains" label="注意事项">
            <Input type="textarea" v-model="form.data.explains" placeholder="请输入注意事项" :rows="8"></Input>
          </FormItem>
          <FormItem prop="hb_image_path" label="活动图片">
            <upload-img v-if="form.visible" @on-change="onUploadImg" :defaultImageList="defaultImageList"></upload-img>
          </FormItem>
        </Form>
      </Col>
    </Row>

    <div slot="footer">
      <!-- <Button @click="closeModal(false)">取消</Button> -->
      <Button type="info" class="fl" @click="prevStep" v-if="currentStep > 1" v-show="!form.data.pkInitial">上一步</Button>
      <Button type="info" @click="nextStep" v-if="currentStep < 2" v-show="!form.data.pkInitial">下一步</Button>

      <Button type="primary" v-if="currentStep === 2" @click="ok">提交</Button>
    </div>
  </Modal>
</template>

<script>
  import Vue from 'vue'
  import { mapGetters } from 'vuex'
  import uploadImg from '@/components/upload-img'
  import codeApi from '@/api/code'
  import yearplanApi from '@/api/yearplan'
  import activityApi from '@/api/activity'
  import clubApi from '@/api/club'

  export default {
    name: 'update-modal',
    props: [
      'form'
    ],
    components: {
      uploadImg
    },
    data () {
      return {
        loading: true,
        yearplanLoading: false,
        yearplanList: [],
        cityList: [],
        countyList: [],
        currentStep: 1,
        matchStatus: '-2',
        ruleValidate: {
          act_name: [
            { required: true, message: '请输入活动名称', trigger: 'change' },
            { min: 1, max: 50, message: '活动名称字符长度应小于50', trigger: 'change' }
          ],
          province: [
            { required: true, message: '请选择省份', trigger: 'change' }
          ],
          city: [
            { required: true, message: '请选择城市', trigger: 'change' }
          ],
          county: [
            { required: true, message: '请选择区县', trigger: 'change' }
          ],
          act_year: [
            { required: true, message: '请选择年度', trigger: 'change' }
          ],
          pk_activity_year_plan: [
            { required: true, message: '请选择年度计划', trigger: 'change' }
          ],
          signup_start_time: [
            { required: true, type: 'date', message: '请选择报名开始时间', trigger: 'change' }
          ],
          signup_end_time: [
            { required: true, type: 'date', message: '请选择报名结束时间', trigger: 'change' }
          ],
          act_start_time: [
            { required: true, type: 'date', message: '请选择活动开始时间', trigger: 'change' }
          ],
          act_end_time: [
            { required: true, type: 'date', message: '请选择活动结束时间', trigger: 'change' }
          ],
          conv_date: [
            { required: true, type: 'date', message: '请选择集合时间', trigger: 'change' }
          ],
          act_sponsor: [
            { required: true, message: '请输入主办方', trigger: 'change' },
            { min: 1, max: 50, message: '主办方字符长度应小于50', trigger: 'change' }
          ],
          act_organizer: [
            { min: 0, max: 50, message: '协办方字符长度应小于50', trigger: 'change' }
          ],
          act_bg: [
            { required: true, message: '请输入活动介绍', trigger: 'change' },
            { min: 1, max: 1000, message: '活动介绍字符长度应小于1000个字', trigger: 'change' }
          ],
          conv_address: [
            { required: true, message: '请输入集合地点', trigger: 'change' },
            { min: 1, max: 50, message: '集合地点字符长度应小于50', trigger: 'change' }
          ],
          sign_up_total: [
            { required: true, type: 'number', message: '请输入拟报名人数', trigger: 'change' }
          ],
          explains: [
            { required: true, message: '请输入注意事项', trigger: 'change' },
            { min: 1, max: 1000, message: '注意事项字符长度应小于1000个字', trigger: 'change' }
          ],
          hb_image_path: [
            { required: true, message: '请上传活动图片', trigger: 'change' }
          ]
        },
        options: {
          act_start_time: {},
          act_end_time: {},
          signup_start_time: {},
          signup_end_time: {}
        }
      }
    },
    computed: {
      ...mapGetters({
        userInfo: 'userInfo',
        areaCodeList: 'areaCodeList',
        actYearCodeList: 'actYearCodeList',
        actTypeCodeList: 'actTypeCodeList',
        actStatusCodeList: 'actStatusCodeList'
      })
    },
    watch: {
      'form.visible': 'onClose',
      'form.data.pkInitial': 'onUpdateShow',
      'form.data.act_year': 'onYearPlanChange',
      'form.data.province': 'getCity',
      'form.data.city': 'getCounty',
      'form.data.act_start_time': function (val, oldVal) {
        this.options.act_end_time.disabledDate = (date) => {
          let isDisabled = false
          if (this.form.data.act_start_time) {
            isDisabled = date && date.valueOf() < this.form.data.act_start_time.getTime()
          }
          return isDisabled
        }
      },
      'form.data.act_end_time': function (val, oldVal) {
        this.options.act_start_time.disabledDate = (date) => {
          let isDisabled = false
          if (this.form.data.act_end_time) {
            isDisabled = date && date.valueOf() > this.form.data.act_end_time.getTime()
          }
          return isDisabled
        }
      },
      'form.data.signup_start_time': function (val, oldVal) {
        this.options.signup_end_time.disabledDate = (date) => {
          let isDisabled = false
          if (this.form.data.signup_start_time) {
            isDisabled = date && date.valueOf() < this.form.data.signup_start_time.getTime()
          }
          return isDisabled
        }
      },
      'form.data.signup_end_time': function (val, oldVal) {
        this.options.signup_start_time.disabledDate = (date) => {
          let isDisabled = false
          if (this.form.data.signup_end_time) {
            isDisabled = date && date.valueOf() > this.form.data.signup_end_time.getTime()
          }
          return isDisabled
        }
      }
    },
    methods: {
      async getCity () {
        let parentid = this.form.data.province
        const { body } = await codeApi.list({
          codeType: 'area',
          parentid
        })
        this.cityList = body.responseData
      },
      async getCounty () {
        let parentId = this.form.data.city
        const { body } = await codeApi.list({
          codeType: 'area',
          parentid: parentId
        })
        this.countyList = body.responseData
      },
      ok () {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.submitForm()
          } else {
            this.$Message.error('表单验证失败，请检查输入项目!')
            this.form.visible = true
            this.loading = false
            setTimeout(() => {
              this.loading = true
            }, 100)
          }
        })
      },
      prevStep () {
        this.currentStep --
      },
      nextStep () {
        this.currentStep ++
      },
      onYearPlanChange (newVal, old) {
        if (old) {
          this.form.data.pk_activity_year_plan = null
        }
        this.getYearPlan('')
      },
      async getYearPlan (query) {
        this.yearplanLoading = true
        const { body } = await yearplanApi.list({
          act_year: this.form.data.act_year,
          act_type: this.form.data.act_type,
          pk_rclub_info: this.userInfo.pkRclubInfo,
          currentPage: 1,
          limit: 500
        })
        let yearplanList = body.responseData.content
        this.$set(this.$data, 'yearplanList', yearplanList)
        this.yearplanLoading = false
      },
      onClose (isVisible) {
        if (!isVisible) {
          this.form.data = {}
          this.currentStep = 1
          this.$refs.form.resetFields()
        } else {
          this.defaultImageList = Vue.filter('splitImg')(this.form.data.hb_image_path || '')
        }
      },
      closeModal () {
        this.form.visible = false
      },
      onUploadImg (imgList) {
        this.form.data.hb_image_path = imgList.filter((item) => {
          return item.name.length > 0
        }).map((item) => {
          if (item.response && item.response.responseData) {
            return item.response.responseData
          } else {
            return item.name
          }
        }).join(',')
        this.$refs.form.validateField('hb_image_path')
      },
      async submitForm () {
        if (this.form.data.pkInitial) {
          const { body } = await activityApi.info.update(this.form.data)
          if (this.$apiHelper.requestSuccessed(body.responseCode)) {
            this.$Message.info('修改成功')
          } else {
            setTimeout(() => {
              this.$Modal.error({
                title: '错误',
                content: body.desc,
                onOk: () => {}
              })
            }, 500)
          }
        } else {
          this.form.data.pk_rclub_info = this.userInfo.pkRclubInfo
          const { body } = await activityApi.info.create(this.form.data)
          if (this.$apiHelper.requestSuccessed(body.responseCode)) {
            this.$Message.info('创建成功')
          } else {
            setTimeout(() => {
              this.$Modal.error({
                title: '错误',
                content: body.desc,
                onOk: () => {}
              })
            }, 500)
          }
        }
        this.form.visible = false
        this.$emit('submit')
      },
      onUpdateShow () {
        // 如果是修改，直接第二步
        if (this.form.data.pkInitial) {
          this.currentStep = 2
        } else { // 否则第一步
          this.currentStep = 1
        }
      },
      async getClubDetail () {
        const { body } = await clubApi.detail({
          pkRclubInfo: this.userInfo.pkRclubInfo
        })
        const { responseData } = body
        if (this.$apiHelper.requestSuccessed(body.responseCode)) {
          this.matchStatus = responseData.matchStatus
        } else {
          setTimeout(() => {
            this.$Modal.error({
              title: '错误',
              content: body.desc,
              onOk: () => {}
            })
          }, 500)
        }
      }
    },
    async mounted () {
      this.$store.dispatch('getCode', 'act_year')
      this.$store.dispatch('getCode', 'act_type')
      this.$store.dispatch('getCode', 'act_status')
      this.$store.dispatch('getCode', 'area')
      this.getYearPlan('')
      this.getClubDetail()
    }
  }
</script>

<style lang="less" scoped>
  .ivu-radio-group-button.ivu-radio-group-large .ivu-radio-wrapper {
    font-size: 16px;
  }

  .step-1 {
    .step-1-con {
      margin: 10px;
      padding: 10px;
      height: 400px;
      border: 1px solid #ccc;
      border-radius: 4px;
    }
  }

  .step-2 {
  }
</style>
